import tornado.web
import asyncio, json
from core.base_tornado_request_handler import BaseTornadoRequestHandler
from db import SchedulesDB

class ApiScheduleHandler(BaseTornadoRequestHandler):
  async def get(self, action):
    if action == "list":
      await self.get_list()
  
  async def post(self, action):
    if action == "clear":
      await self.clear_role()
      return
    if action == "delete":
      await self.delete_role()
      return
    if action == "update":
      await self.update_role()

  async def get_list(self):
    role_list = await SchedulesDB.all()
    self.return_json({"list": [role.to_dict() for role in role_list]})

  async def update_role(self):
    data = json.loads(self.request.body) if self.request.body else {}
    role_id = data.get("id", 0)
    if role_id == 0:
      role = await SchedulesDB.create(**data)
      self.return_json({"role": role.to_dict()})
      return
    filter_role = await SchedulesDB.filter(id=role_id).get_or_none()
    if filter_role is None:
      self.return_json(data=None, code=403, status=False, message="角色不存在")
      return
    # normal_data = {k: v for k, v in data.items() if k != "id"}
    filter_role.update_from_dict(data)
    await filter_role.save()
    self.return_json({"role": filter_role.to_dict()})

  async def clear_role(self):
    num = await SchedulesDB.all().delete()
    self.return_json({"num": num})

  async def delete_role(self):
    data = json.loads(self.request.body) if self.request.body else {}
    role_id = data.get("id", 0)
    num = await SchedulesDB.filter(id=role_id).delete()
    self.return_json({"num": num})
  